package com.springboot.distributed.filter.dubbo;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.springboot.distributed.constant.TransactionConstants;
import com.springboot.distributed.transaction.util.DistributedTransactionManager;

/**
 * 分布式事务dubbo过滤器
 * order 值越小优先级越高，这里要设置高于ConsumerContextFilter的-10000的优先级
 *
 * @author supu
 * @date 2019-09-05 16:10
 **/
@Activate(group = Constants.CONSUMER, order = -20000)
public class DistributedTransactionConsumerFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(DistributedTransactionConsumerFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String uniqueKey = DistributedTransactionManager.getUniqueKey();
        if (StringUtils.isNotEmpty(uniqueKey)) {
            // 设置事务唯一标记
            RpcContext.getContext().setAttachment(TransactionConstants.UNIQUE_KEY, uniqueKey);
        }
        logger.info("distributedTransaction filter is run, uniqueKey:{}", uniqueKey);
        return invoker.invoke(invocation);
    }
}
